//
//  TTImageDingzhiUploadView.m
//  TaoTuo
//
//  Created by 刘广 on 2020/3/27.
//  Copyright © 2020 刘广. All rights reserved.
//

#import "TTImageDingzhiUploadView.h"
#import "TTImageDingzhiUploadViewCell.h"
#import "TTImageDingzhiCountViewCell.h"
#import "LLImagePicker.h"
#import "OSSImageUploader.h"
#import <Photos/Photos.h>

static NSString *uploadCell = @"uploadCell";
static NSString *countCell = @"countCell";

@interface TTImageDingzhiUploadView ()<UICollectionViewDelegate, UICollectionViewDataSource, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    TTImageDingzhiModel *addModel;
    TTImageDingzhiModel *addVideoModel;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *datasArray;

@end

@implementation TTImageDingzhiUploadView


- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
//        self.backgroundColor = [UIColor cyanColor];
        self.images = [NSMutableArray array];
        [self setupDatas];
        
    }
    return self;
}

- (void)reloadView
{
    [self.collectionView reloadData];
    
    CGFloat h = ceil(self.datasArray.count / 3.0) * 80 + 10;
    self.collectionView.height = h;
    self.height = h;
    
    if (self.getContentHeightBlock) {
        self.getContentHeightBlock(h);
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.datasArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTImageDingzhiModel *model = self.datasArray[indexPath.row];
    if (model.imageName.length > 0) {
        
        TTImageDingzhiCountViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:countCell forIndexPath:indexPath];
        cell.model = model;
        return cell;
        
    } else {
        TTImageDingzhiUploadViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:uploadCell forIndexPath:indexPath];
        cell.model = model;
        @weakify(self)
        cell.deleteBlock = ^(TTImageDingzhiModel * _Nonnull model) {
            @strongify(self)
            if (model.isImage) {
                self->addModel.count++;
            } else if (model.isVideo) {
                [self.datasArray addObject:self->addVideoModel];
            }
            [self.datasArray removeObject:model];
            [self reloadView];
        };
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTImageDingzhiModel *model = self.datasArray[indexPath.row];
    if (model.isAddImage && model.count > 0) {
        
        [LLImagePicker imagePickerWithMaxImagesCount:model.count delegate:self baseViewController:self.viewController didFinishPickingPhotosHandle:^(NSArray<UIImage *> * _Nonnull photos, BOOL isSelectOriginalPhoto) {
            //上传图片到OSS, 添加model
            [[OSSImageUploader sharedLoader] asyncUploadImages:photos complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
                NSLog(@">>>> %@, state = %ld", names, state);
                for (NSString *urlStr in names) {
                    TTImageDingzhiModel *model = [[TTImageDingzhiModel alloc] init];
                    model.urlString = urlStr;
                    model.isImage = YES;
                    NSInteger addIndex = [self.datasArray indexOfObject:self->addModel];
                    [self.datasArray insertObject:model atIndex:addIndex];
                    
                    NSDictionary *dic = @{
                        @"ImageUrl" : urlStr,
                        @"FileType" : @0
                    };
                    [self.images addObject:dic];
                }

                [self reloadView];
            }];
        }];
        
    } else if (model.isVideo && model.imageName.length > 0) {
        
        UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
        pickerController.delegate = self;
//        pickerController.videoMaximumDuration = 15.0;//视频最长长度
        pickerController.videoQuality = UIImagePickerControllerQualityTypeMedium;//视频质量
        //媒体类型：@"public.movie" 为视频  @"public.image" 为图片
        //这里只选择展示视频
        pickerController.mediaTypes = [NSArray arrayWithObjects:@"public.movie", nil];
        
        pickerController.sourceType= UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        pickerController.allowsEditing = NO;
        [[LLRouteTool getCurrentNavigationController] presentViewController:pickerController animated:YES completion:nil];
        
    } else {
        
    }
}

// 拍照或选取图片完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    /// 视频
    if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.movie"]) {
        
        NSURL *videoUrl = info[UIImagePickerControllerMediaURL];
        NSData *data = [NSData dataWithContentsOfURL:videoUrl];
        
        ///视频长度
        AVAsset *asset = [AVAsset assetWithURL:videoUrl];
        CMTime totalTime = asset.duration;
        CGFloat totalTimeSeconds = (CGFloat)totalTime.value / totalTime.timescale;
        
        UIImage *image = [self getScreenShotImageFromVideoPath:videoUrl];
        
        [MBProgressHUD showLoadingAnimationOnView:self];
        @weakify(self)
        [[OSSImageUploader sharedLoader] asyncUploadVideo:data progress:^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
            
        } complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
            @strongify(self)
            [MBProgressHUD dismissAnimationOnView:self];
            
            if (state == UploadImageSuccess) {
                NSString *urlStr = names.firstObject;
                TTImageDingzhiModel *model = [[TTImageDingzhiModel alloc] init];
                model.urlString = urlStr;
                model.isVideo = YES;
                model.thumbImage = image;
                model.videoTime = totalTimeSeconds;
                NSInteger addIndex = [self.datasArray indexOfObject:self->addModel];
                [self.datasArray insertObject:model atIndex:addIndex];
                [self.datasArray removeLastObject];
                [self reloadView];
                
                NSDictionary *dic = @{
                    @"ImageUrl" : urlStr,
                    @"FileType" : @1
                };
                [self.images addObject:dic];
                
            }
            
        }];
        
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        return;
    }
    // 图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    //上传图片到OSS, 添加model
    [MBProgressHUD showLoadingAnimationOnView:self];
    @weakify(self)
    [[OSSImageUploader sharedLoader] asyncUploadImage:image complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
        @strongify(self)
        [MBProgressHUD dismissAnimationOnView:self];
        
        self->addModel.count--;
        NSString *urlStr = names.firstObject;
        TTImageDingzhiModel *model = [[TTImageDingzhiModel alloc] init];
        model.urlString = urlStr;
        model.isImage = YES;
        NSInteger addIndex = [self.datasArray indexOfObject:self->addModel];
        [self.datasArray insertObject:model atIndex:addIndex];
        [self reloadView];
        
        NSDictionary *dic = @{
            @"ImageUrl" : urlStr,
            @"FileType" : @0
        };
        [self.images addObject:dic];
        
    }];
    
}

// 获取缩略图
- (UIImage *)getScreenShotImageFromVideoPath:(NSURL *)fileURL
{

    UIImage *shotImage;

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];

    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];

    gen.appliesPreferredTrackTransform = YES;

    CMTime time = CMTimeMakeWithSeconds(0.0, 600);

    NSError *error = nil;

    CMTime actualTime;

    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];

    shotImage = [[UIImage alloc] initWithCGImage:image];

    CGImageRelease(image);

    return shotImage;

}

- (void)setupDatas
{
    [self.datasArray removeAllObjects];
    
    addModel = [[TTImageDingzhiModel alloc] init];
    addModel.isAddImage = YES;
    addModel.imageName = @"xiangji";
    addModel.count = 6;
    [self.datasArray addObject:addModel];
    
    addVideoModel = [[TTImageDingzhiModel alloc] init];
    addVideoModel.isVideo = YES;
    addVideoModel.imageName = @"shipin";
    addVideoModel.hintStr = @"添加短视频";
    [self.datasArray addObject:addVideoModel];
    
    [self.collectionView reloadData];
}


- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(80, 80);
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
//        layout.sectionInset = UIEdgeInsetsMake(0, 10, 10, 10);
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        _collectionView.frame = self.bounds;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[TTImageDingzhiUploadViewCell class] forCellWithReuseIdentifier:uploadCell];
        [_collectionView registerClass:[TTImageDingzhiCountViewCell class] forCellWithReuseIdentifier:countCell];
        [self addSubview:_collectionView];
        
    }
    return _collectionView;
}

- (NSMutableArray *)datasArray
{
    if (!_datasArray) {
        _datasArray = [NSMutableArray array];
    }
    return _datasArray;
}


@end
